import React, {Component} from 'react';
import {StyleSheet, View, Text, ImageBackground, Image} from 'react-native';
import screen from '../../../utils/screen';
import Images from '../../../images/images';
import TouchableView from '../../../components/touchableView';

const pointerScale = 248 / 100
const pointerWidth = screen.PIXEL_60
const pointerHeight = pointerWidth * pointerScale
const outSpace = screen.scaleSize(78)
const satInfoWidth = screen.scaleSize(218)

export class WatchComponent extends Component {

    constructor(props) {
        super(props);
        this.getSatView = this.getSatView.bind(this)
        this.checkIsRecommend = this.checkIsRecommend.bind(this)
        this.handleSatList = this.handleSatList.bind(this)
        this.state = {
            data:[],
            selSat:null
        }
    }

    componentDidMount() {

    }

    UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
        const {satList,width,heading} = nextProps
        this.handleSatList(satList,width,heading)
    }

    //处理卫星位置,重叠
    handleSatList(list,width,heading){

        let radius = Math.PI / 180;
        let newList = [],posList = [],onlineSatList = []
        let itemWidth,itemHeight,circleWidth,isOnline
        let isRecommend = true
        let hasValidator = {showId:null,count:0}
        list.forEach((item,index)=>{
            let {azimuth,elevation} = item
            if(elevation >= 0){
                // console.log('onLine item:',item);
                //过境卫星
                itemWidth = screen.PIXEL_70
                itemHeight = screen.PIXEL_70
                circleWidth = width - outSpace * 2
                isOnline = true
                isRecommend = this.checkIsRecommend(item)
            }else{
                itemWidth = screen.PIXEL_60;
                itemHeight = screen.PIXEL_60;
                circleWidth = width;
                isOnline = false
            }

            let itemLeft = width / 2 + (circleWidth / 2) * Math.sin(radius * azimuth) - itemWidth / 2;
            let itemTop = width / 2 - (circleWidth / 2) * Math.cos(radius * azimuth) - itemHeight / 2;

            let pos = {itemLeft, itemTop, itemWidth, itemHeight,id:item.id}
            if(!isOnline) {
                hasValidator = this.checkHasValidator(pos, posList)
                posList.push(pos)
            }else{
                hasValidator = this.checkHasValidator(pos, onlineSatList)
                onlineSatList.push(pos)
            }


            const satRotate = azimuth - heading

            let obj = {...item,satRotate,isOnline,isRecommend,pos}
            if(hasValidator.count < 1){
                newList.push(obj)
            }else{
                if(hasValidator.showId ){
                    // console.log('重叠',hasValidator)
                    const showItem = newList.find(it=>{
                        return it.id === hasValidator.showId
                    })
                    if(showItem){
                        if(!showItem.subItems){
                            showItem.subItems = []
                        }
                        showItem.subItems.push(obj)
                    }

                    // console.log('showItem',showItem);
                }

            }

        })
        // console.log('newlist:',newList);
        this.setState({
            data:newList
        })
    }

    componentWillUnmount() {

    }


    getDirection(){
        let radius = Math.PI / 2;
        let itemWidth = screen.scaleSize(60);
        let itemHeight = screen.scaleSize(60);
        const {width,heading} = this.props

        const offset = screen.PIXEL_80
        const circleWidth = width - offset
        let list = ['N', 'E', 'S', 'W'];
        return list.map((item, index) => {
            let itemLeft = width / 2 + circleWidth / 2 * Math.sin(radius * index) - itemWidth / 2;
            let itemTop = width / 2 - circleWidth / 2 * Math.cos(radius * index) - itemHeight / 2;

            return (
                <View
                    key={index}
                    style={{
                        position: 'absolute',
                        top: itemTop    ,
                        left: itemLeft  ,
                        width: itemWidth,
                        height: itemHeight,
                        justifyContent: 'center',
                        alignItems: 'center',
                        // borderWidth:1,borderColor:'red',
                        transform: [{rotate: heading + 'deg'}],
                    }}
                >
                    <Text style={{color: index === 0 ? 'red' : '#464E64', fontSize: screen.PIXEL_50, fontWeight: '500'}}>
                        {item}
                    </Text>
                </View>
            )
        })
    }

    getSatView(){
        const {data,selSat} = this.state
        const {heading} = this.props
        if(!data.length) return null

        return data.map((item,index)=>{
            let {azimuth,elevation,startTime,endTime,restMinutes,clockwise,isRecommend,isOnline,
                pos:{itemLeft, itemTop, itemWidth, itemHeight},satRotate,subItems} = item


            return  (
                <TouchableView
                    key={index}
                    style={{
                        position: 'absolute',
                        top: itemTop,
                        left: itemLeft,
                        // borderWidth:1,borderColor:'red',
                        transform: [{rotate: heading + 'deg'},
                            // {scale: selSat && selSat.id === item.id ? 1.2 : 1}
                            ],
                        zIndex:isOnline ? 100 : 1
                    }}
                    onPress={()=>{
                        if(item.subItems && item.subItems.length){
                            this.setState({
                                selSat:item
                            })
                        }

                        this.props.onItemClick && this.props.onItemClick(item)
                    }}
                >
                    {
                        isOnline ? (
                            <>
                                <Image source={ Images.sat_in }
                                       style={{width:itemWidth,height:itemHeight,
                                           transform:[{rotate: (clockwise ? satRotate + 210 : satRotate +  30) +'deg'}]
                                       }}/>
                                <View style={[styles.satInfoView,{width:satInfoWidth,top:itemHeight+5,left:-satInfoWidth / 2 + itemWidth / 2}]}>
                                    <View style={styles.angleWrap}>
                                        <Image source={Images.angle} style={styles.angleImg} resizeMode={'contain'}/>
                                        <Text style={styles.angleText}>{parseInt(elevation)}°</Text>
                                    </View>
                                    <View style={styles.line}/>
                                    <View style={styles.angleWrap}>
                                        <Image source={Images.time} style={styles.angleImg} resizeMode={'contain'}/>
                                        <Text style={styles.angleText}>{restMinutes}{'\n'}
                                            <Text style={{fontSize:8}}>min</Text>
                                        </Text>
                                    </View>
                                </View>
                                {
                                    isRecommend  && (
                                        <View style={styles.recommendBg}>
                                            <Text style={{color:'#fff',fontSize:screen.PIXEL_18,textAlignVertical:'center'}}>推荐</Text>
                                        </View>
                                    )
                                }
                                {
                                    subItems && subItems.length > 0 ? (
                                        <View style={{width:5,height:5,backgroundColor:'red'}}/>
                                    ) : null
                                }
                            </>
                        ) : (
                            <>
                                <Image source={Images.sat_out}
                                       style={{width:itemWidth,height:itemHeight,
                                           transform:[{rotate: (clockwise ? satRotate -30: satRotate + 180 -30) +'deg'}]
                                       }}
                                />
                                {
                                    subItems && subItems.length > 0 ? (
                                        <View style={[styles.subSatCountBg,{
                                            left:-5 + itemWidth / 2,top:itemHeight,width:10,position:'absolute'
                                        }]}>
                                            <Text style={{color:'#fff',fontSize:screen.PIXEL_16,textAlignVertical:'center'}}>{subItems.length + 1}</Text>
                                        </View>
                                    ) : (
                                        <View style={[styles.satOutTimeWrap,
                                            {left:-screen.PIXEL_50 + itemWidth / 2,top:itemHeight,width:screen.PIXEL_100,position:'absolute'}
                                        ]}>
                                            <Image source={Images.rest_time} style={styles.restTimeImg} resizeMode={'contain'} />
                                            <Text style={[styles.restTimeText]}
                                                  numberOfLines={1}>{startTime}</Text>
                                        </View>
                                    )
                                }



                            </>
                        )
                    }

                </TouchableView>
            )
        })
    }
   /* getSatView(){
        const {satList,width,heading} = this.props
        if(!satList.length) return null
        let radius = Math.PI / 180;
        let posList = []
        let onlineSatList = []
        let itemWidth,itemHeight,circleWidth,isOnline
        let isRecommend = true
        let hasValidator = {showIndex:-1,count:0}
        return satList.map((item,index)=>{
            let {azimuth,elevation,startTime,endTime,restMinutes,clockwise} = item

            if(elevation >= 0){

                // console.log('onLine item:',item);
                //过境卫星
                itemWidth = screen.PIXEL_70
                itemHeight = screen.PIXEL_70
                circleWidth = width - outSpace * 2
                isOnline = true
                isRecommend = this.checkIsRecommend(item)
            }else{
                itemWidth = screen.PIXEL_60;
                itemHeight = screen.PIXEL_60;
                circleWidth = width;
                isOnline = false
            }

            let itemLeft = width / 2 + (circleWidth / 2) * Math.sin(radius * azimuth) - itemWidth / 2;
            let itemTop = width / 2 - (circleWidth / 2) * Math.cos(radius * azimuth) - itemHeight / 2;

            let pos = {itemLeft, itemTop, itemWidth, itemHeight}
            if(!isOnline) {
                hasValidator = this.checkHasValidator(pos, posList)
                posList.push(pos)
            }else{
                hasValidator = this.checkHasValidator(pos, onlineSatList)
                onlineSatList.push(pos)
            }

            const satRotate = azimuth - heading
            return hasValidator.count > 0 ? null : (
                <View
                    key={index}
                    style={{
                        position: 'absolute',
                        top: itemTop,
                        left: itemLeft,
                        borderWidth:1,borderColor:'red',
                        transform: [{rotate: heading + 'deg'}],
                        zIndex:isOnline ? 100 : 1
                    }}
                >
                    {
                        isOnline ? (
                            <>
                                <Image source={ Images.sat_in }
                                       style={{width:itemWidth,height:itemHeight,
                                        transform:[{rotate: (clockwise ? satRotate + 210 : satRotate +  30) +'deg'}]
                                       }}/>
                                <View style={[styles.satInfoView,{width:satInfoWidth,top:itemHeight+5,left:-satInfoWidth / 2 + itemWidth / 2}]}>
                                    <View style={styles.angleWrap}>
                                        <Image source={Images.angle} style={styles.angleImg} resizeMode={'contain'}/>
                                        <Text style={styles.angleText}>{parseInt(elevation)}°</Text>
                                    </View>
                                    <View style={styles.line}/>
                                    <View style={styles.angleWrap}>
                                        <Image source={Images.time} style={styles.angleImg} resizeMode={'contain'}/>
                                        <Text style={styles.angleText}>{restMinutes}{'\n'}
                                            <Text style={{fontSize:8}}>min</Text>
                                        </Text>
                                    </View>
                                </View>
                                {
                                    isRecommend  && (
                                        <View style={styles.recommendBg}>
                                            <Text style={{color:'#fff',fontSize:screen.PIXEL_18,textAlignVertical:'center'}}>推荐</Text>
                                        </View>
                                    )
                                }
                                {
                                    hasValidator.showIndex === index ? (
                                        <View style={{width:5,height:5,backgroundColor:'red'}}/>
                                    ) : null
                                }
                            </>
                        ) : (
                            <>
                                <Image source={Images.sat_out}
                                       style={{width:itemWidth,height:itemHeight,
                                           transform:[{rotate: (clockwise ? satRotate -30: satRotate + 180 -30) +'deg'}]
                                       }}
                                />
                                <View style={[styles.satOutTimeWrap,
                                    {left:-screen.PIXEL_50 + itemWidth / 2,top:itemHeight,width:screen.PIXEL_100,position:'absolute'}
                                    ]}>
                                    <Image source={Images.rest_time} style={styles.restTimeImg} resizeMode={'contain'} />
                                    <Text style={[styles.restTimeText]}
                                          numberOfLines={1}>{startTime}</Text>
                                </View>

                                {
                                    hasValidator.showIndex === index ? (
                                        <View style={{width:5,height:5,backgroundColor:'red'}}/>
                                    ) : null
                                }

                            </>
                        )
                    }

                </View>
            )
        })
    }
*/
    //判断是否有重叠元素
    checkHasValidator = (pos,posList)=>{

        let count = 0
        let showIndex = -1
        posList.forEach((data,index)=>{
            const {itemLeft,itemTop,itemWidth,itemHeight} = data
            if(Math.abs(pos.itemLeft - itemLeft) < itemWidth &&
                Math.abs(pos.itemTop - itemTop) < itemHeight
            ){
                if(showIndex === -1){
                    showIndex = index
                }
                count += 1
            }
        })

        return {count,showId:showIndex > -1 ? posList[showIndex].id : null}
    }

    //判断是否是推荐的卫星
    checkIsRecommend = (item)=>{
        let res = true
        this.props.satList.forEach(it=>{
            if(it.elevation > 0 && it.id !== item.id){
                res = item.duration > it.duration ? true : false
            }
        })

        return res
    }

    render(){
        const circleWidth = this.props.width;
        const heading  = this.props.heading
        return(
            <View style={[this.props.style,{width:this.props.width,height:this.props.width}]}>
                <ImageBackground
                    source={Images.sat_bg}
                    imageStyle={{width:this.props.width, height:this.props.width}}
                    style={[this.props.style,{
                            width:this.props.width,
                            height:this.props.width,
                            transform: [{rotate: -heading + 'deg'}],
                        }
                    ]}
                >
                    {this.getDirection()}
                    {this.getSatView()}

                </ImageBackground>

                <Image
                    source={Images.pointer}
                    style={{
                    position:'absolute',
                    top:circleWidth/2 - pointerHeight + pointerWidth / 2  ,
                    left:(circleWidth-pointerWidth)/2,
                    width:pointerWidth,
                    height:pointerHeight,
                }}>

                </Image>
            </View>
        )
    }
}


const styles = StyleSheet.create({

    satInfoView:{
        position:'absolute',backgroundColor: 'rgba(0,0,0,0.40)',height:screen.PIXEL_60,
        borderRadius:screen.PIXEL_30,flexDirection:'row',alignItems:'center',paddingHorizontal:screen.PIXEL_24
    },
    angleWrap:{
        flex:1,flexDirection:'row',alignItems:'center',justifyContent:'center'
    },
    line:{
        width:1,height:screen.PIXEL_30,backgroundColor:'#fff',marginHorizontal:5
    },
    angleText:{
        color:'#fff',fontWeight:'500',fontSize: 12,textAlign: 'center',marginLeft:5
    },
    angleImg:{
        width:screen.PIXEL_30,height:screen.PIXEL_30
    },
    recommendBg:{
        position:'absolute',top:-screen.PIXEL_10,right:-screen.PIXEL_18,
        backgroundColor:'#F1413E',width:screen.PIXEL_50,height:screen.PIXEL_24,
        borderRadius: screen.PIXEL_10,justifyContent: 'center',alignItems:'center'
    },
    satOutTimeWrap:{
        flexDirection:'row',justifyContent:'center',alignItems:'center'
    },
    restTimeImg:{
        width:screen.PIXEL_24,height:screen.PIXEL_24,marginRight:screen.PIXEL_4
    },
    restTimeText:{
        color:'#A0A0A0',fontSize:11,textAlign:'center'
    },
    subSatCountBg:{
        width:10,height:10,backgroundColor:'red',borderRadius:10,justifyContent:'center',alignItems:'center',
        // position:'absolute',top:0,left:0
    }
})
